class BlogController < ApplicationController
  layout :theme_layout
  
  before_filter :setup_themer, :content_for_layout
  session :off
  
  def index
    @entries = paginate_entries(@blog.entries)
  end

  def show
    @entry = Entry.find(params[:id])
    @entry.count += 1
    @entry.save!
    @comment = Comment.new(:commentable_id => @entry.id)
  end
  
  def create_comment
    if request.post?
      comment = Comment.new(params[:comment])
      comment.remote_ip = request.remote_ip
      entry = Entry.find(params[:comment][:commentable_id])
      if entry.comments << comment
        flash[:notice] = "Comment saved."
        redirect_to :action => :show, :id => params[:comment][:commentable_id], :anchor => "comment-#{comment.id}"
      else
        @entry = entry
        @comment = comment
        render :action => :show
      end
    end
    
  end

  def category
    @entries = paginate_entries(Category.find(params[:id]).entries)
    render_entries_list
  end

  def tag
    @entries = paginate_entries(Entry.find_tagged_with(params[:id], 
        :conditions => ["entries.category_id in (select categories.id from categories where categories.blog_id = ?)", @blog.id]))
    render_entries_list
  end

  def archive
    @entries = paginate_entries(@blog.entries_created_in(params[:year], params[:month]))
    render_entries_list
  end
  
  def feed
    @entries = @blog.latest_entries(@blog.recent_entries)
    render(:layout => false)
  end
  
  def comment_feed
    @comments = @blog.latest_comments(@blog.recent_comments)
    render(:layout => false)
  end
  
  private
  def render_entries_list
    render :action => :index
  end
  
  def paginate_entries(entries)
    entries.paginate :per_page => @blog.entries_per_page, 
      :page => params[:page], :order => "created_at DESC"
  end
  
  def content_for_layout
    @blog = User.find_by_name(params[:user]).blog
  end
  
  def top_entries
    @top_entries = @blog.entries.find_tagged_with('top')
  end
end
